/**
 * 
 */
package com.playball.lottery.frm.yhzx;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.playball.lottery.R;
import com.playball.lottery.ApplicationData;
import com.playball.lottery.base.BaseActivity;
import com.playball.lottery.customview.ShowTipDialog;
import com.playball.lottery.nt.GetRequestParams;
import com.playball.lottery.util.ConvertJsonToList;


/**
 * @author sunfanglei
 * @date 2014年3月27日
 */
public class SavedPlanDetailActivity extends BaseActivity {

	TextView tv_savedplan_bet_content;
	TextView tv_savedplan_endtime;
	TextView tv_savedplan_issue;
	TextView tv_savedplan_allmoney;
	EditText et_savedplan_buymoney;
	TextView tv_savedplan_buymoney_per;
	CheckBox cb_savedplan_zigou;
	TextView tv_savedplan_yjbi;
	View layout_bt_yjbl;
	TextView tv_savedplan_isshow_yjbl;
	String SchemeID = "";
	int alMoney = 0;

	int yjbiIndex = 0;

	Button bt0;
	Button bt1;
	Button bt2;
	Button bt3;
	Button bt4;
	Button bt5;
	Button bt6;
	Button bt7;
	Button bt8;
	Button bt9;
	Button bt10;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.jddsavedplandetail);
		TextView info = (TextView) findViewById(R.id.top_title_info);
		TextView back = (TextView) findViewById(R.id.top_title_back);
		back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				onKeyDown(KeyEvent.KEYCODE_BACK, null);
			}
		});

		TextView right = (TextView) findViewById(R.id.bottom_right_btn);
		right.setBackgroundResource(R.drawable.jdd_btn_bg_red);
		right.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AsyncLoaderBuy asyncLoaderBuy = new AsyncLoaderBuy();
				String[] dyn = new String[2];
				JSONObject params = new JSONObject();
				try {
					params.put("SchemeID", SchemeID);// 1
					params.put("BuyShare", et_savedplan_buymoney.getText().toString());
					params.put("BonusScale", yjbiIndex);
				} catch (JSONException ex) {
					// TODO Auto-generated catch block
					Log.e("error", ex.toString());
				}
				dyn[0] = params.toString();
				dyn[1] = "213";// 116
				asyncLoaderBuy.execute(dyn);

			}
		});

		tv_savedplan_bet_content = (TextView) findViewById(R.id.tv_savedplan_bet_content);
		tv_savedplan_endtime = (TextView) findViewById(R.id.tv_savedplan_endtime);
		tv_savedplan_issue = (TextView) findViewById(R.id.tv_savedplan_issue);
		tv_savedplan_allmoney = (TextView) findViewById(R.id.tv_savedplan_allmoney);
		et_savedplan_buymoney = (EditText) findViewById(R.id.et_savedplan_buymoney);
		tv_savedplan_buymoney_per = (TextView) findViewById(R.id.tv_savedplan_buymoney_per);
		cb_savedplan_zigou = (CheckBox) findViewById(R.id.cb_savedplan_zigou);
		tv_savedplan_yjbi = (TextView) findViewById(R.id.tv_savedplan_yjbi);
		layout_bt_yjbl = findViewById(R.id.layout_bt_yjbl);
		tv_savedplan_isshow_yjbl = (TextView) findViewById(R.id.tv_savedplan_isshow_yjbl);
		Intent intent = getIntent();
		tv_savedplan_allmoney.setText(intent.getStringExtra("Money"));
		tv_savedplan_issue.setText(intent.getStringExtra("IssueName"));
		info.setText(intent.getStringExtra("lotName") + "待发起方案");
		tv_savedplan_endtime.setText(intent.getStringExtra("BuyEndTime"));
		SchemeID = intent.getStringExtra("SchemeID");

		View.OnClickListener btListener = new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				btnClickByID(v.getId());
			}
		};
		bt0 = (Button) findViewById(R.id.bt0);
		bt1 = (Button) findViewById(R.id.bt1);
		bt2 = (Button) findViewById(R.id.bt2);
		bt3 = (Button) findViewById(R.id.bt3);
		bt4 = (Button) findViewById(R.id.bt4);
		bt5 = (Button) findViewById(R.id.bt5);
		bt6 = (Button) findViewById(R.id.bt6);
		bt7 = (Button) findViewById(R.id.bt7);
		bt8 = (Button) findViewById(R.id.bt8);
		bt9 = (Button) findViewById(R.id.bt9);
		bt10 = (Button) findViewById(R.id.bt10);
		bt0.setOnClickListener(btListener);
		bt1.setOnClickListener(btListener);
		bt2.setOnClickListener(btListener);
		bt3.setOnClickListener(btListener);
		bt4.setOnClickListener(btListener);
		bt5.setOnClickListener(btListener);
		bt6.setOnClickListener(btListener);
		bt7.setOnClickListener(btListener);
		bt8.setOnClickListener(btListener);
		bt9.setOnClickListener(btListener);
		bt10.setOnClickListener(btListener);

		try {
			alMoney = Integer.parseInt(intent.getStringExtra("Money"));
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
		}
		int moneytemp = (alMoney * 5 / 100);
		if (moneytemp * 20 < alMoney) {
			moneytemp = moneytemp + 1;
		}
		et_savedplan_buymoney.setText("" + moneytemp);
		float temp = Float.parseFloat(et_savedplan_buymoney.getText().toString());
		temp = temp * 100 / alMoney;
		tv_savedplan_buymoney_per.setText("" + new DecimalFormat("#0.00").format(temp));
		startDetailThread();

		cb_savedplan_zigou.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				// TODO Auto-generated method stub
				try {
					if (isChecked == true) {
						et_savedplan_buymoney.setText("" + (alMoney));
					}
					if (isChecked == false && Integer.parseInt(et_savedplan_buymoney.getText().toString()) == alMoney) {
						et_savedplan_buymoney.setText("0");
					}
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					// e.printStackTrace();
				}
			}
		});

		et_savedplan_buymoney.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				try {
					if (s.length() == 0) {
						et_savedplan_buymoney.setText("0");
					} else {
						int money = Integer.parseInt(s.toString());
						if (money > alMoney) {
							String curMon = s.subSequence(start, start + count).toString();
							if (Integer.parseInt(curMon.toString()) >= alMoney) {
								et_savedplan_buymoney.setText("" + alMoney);
								cb_savedplan_zigou.setChecked(true);
							} else {
								et_savedplan_buymoney.setText(curMon);
							}
						}
						String str = et_savedplan_buymoney.getText().toString();
						try {
							Integer.parseInt(str);

						} catch (Exception e) {
							// TODO: handle exception
							et_savedplan_buymoney.setText("0");
						}
					}
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					// e.printStackTrace();
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				// String string = et_savedplan_buymoney.getText().toString();
				// int money = Integer.parseInt(string);
				// if (money > alMoney) {
				// et_savedplan_buymoney.setText("" + alMoney);
				// cb_savedplan_zigou.setChecked(true);
				// }else
				// if (money < alMoney * 5 / 100) {
				// int newmoney = money;
				// if(money*20 < alMoney){
				// System.out.println("money:"+money);
				// newmoney = alMoney * 5 / 100 + 1;
				// }
				// System.out.println("newmoney"+newmoney);
				// et_savedplan_buymoney.setText("" + newmoney);
				// }

				if (et_savedplan_buymoney.getText().equals("")) {
					tv_savedplan_buymoney_per.setText("" + 0);
				} else {
					float temp = Float.parseFloat(et_savedplan_buymoney.getText().toString());
					if (temp < alMoney) {
						cb_savedplan_zigou.setChecked(false);
					} else {
						cb_savedplan_zigou.setChecked(true);
					}
					temp = temp * 100 / alMoney;
					tv_savedplan_buymoney_per.setText("" + new DecimalFormat("#0.00").format(temp));
				}
			}
		});

		tv_savedplan_isshow_yjbl.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (layout_bt_yjbl.isShown() == true) {
					layout_bt_yjbl.setVisibility(View.GONE);
					tv_savedplan_isshow_yjbl.setText("<^>");
				} else {
					layout_bt_yjbl.setVisibility(View.VISIBLE);
					tv_savedplan_isshow_yjbl.setText("<V>");
				}
			}
		});

	}

	public void onResume() {
		super.onResume();
		
	}

	public void onPause() {
		super.onPause();
		
	}

	protected void btnClickByID(int id) {
		// TODO Auto-generated method stub
		bt0.setSelected(false);
		bt1.setSelected(false);
		bt2.setSelected(false);
		bt3.setSelected(false);
		bt4.setSelected(false);
		bt5.setSelected(false);
		bt6.setSelected(false);
		bt7.setSelected(false);
		bt8.setSelected(false);
		bt9.setSelected(false);
		bt10.setSelected(false);
		switch (id) {
		case R.id.bt0:
			yjbiIndex = 0;
			bt0.setSelected(true);
			break;
		case R.id.bt1:
			yjbiIndex = 1;
			bt1.setSelected(true);
			break;
		case R.id.bt2:
			yjbiIndex = 2;
			bt2.setSelected(true);
			break;
		case R.id.bt3:
			yjbiIndex = 3;
			bt3.setSelected(true);
			break;
		case R.id.bt4:
			yjbiIndex = 4;
			bt4.setSelected(true);
			break;
		case R.id.bt5:
			yjbiIndex = 5;
			bt5.setSelected(true);
			break;
		case R.id.bt6:
			yjbiIndex = 6;
			bt6.setSelected(true);
			break;
		case R.id.bt7:
			yjbiIndex = 7;
			bt7.setSelected(true);
			break;
		case R.id.bt8:
			yjbiIndex = 8;
			bt8.setSelected(true);
			break;
		case R.id.bt9:
			yjbiIndex = 9;
			bt9.setSelected(true);
			break;
		case R.id.bt10:
			yjbiIndex = 10;
			bt10.setSelected(true);
			break;
		default:
			break;
		}
		tv_savedplan_yjbi.setText("当前佣金比例为" + yjbiIndex + "%");
	}

	public void startDetailThread() {
		AsyncLoader task = new AsyncLoader();
		String[] dyn = new String[2];
		JSONObject params = new JSONObject();
		try {
			params.put("DataSource", "1");// 1
			params.put("SchemeID", SchemeID);
		} catch (JSONException ex) {
			// TODO Auto-generated catch block
			Log.e("error", ex.toString());
		}
		dyn[0] = params.toString();
		dyn[1] = "210";// 116
		task.execute(dyn);
	}

	class AsyncLoaderBuy extends AsyncTask<String, Integer, String> {// 继承AsyncTask
		String action;
		ShowTipDialog showdialog = new ShowTipDialog();

		// 1.准备运行
		protected void onPreExecute() {
			showdialog.showDialog(SavedPlanDetailActivity.this);
		}

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			action = params[1];
			// 处理后台执行的任务，在后台线程执行
			String strResult = null;
			// 获取请求返回值
			String UserID = ApplicationData.getInstance().getUserID();
			strResult = GetRequestParams.getRequestUserIDResult(params[0], UserID, action, getApplicationContext());
			// 获取请求返回值
			return strResult;
		}

		protected void onPostExecute(String result) {
			showdialog.closeDialog();
			if (result != null) {
				try {
					JSONTokener jsonParser = new JSONTokener(result);
					JSONObject js = (JSONObject) jsonParser.nextValue();
					if (Integer.parseInt(js.getString("Code")) == 0) {
						Toast.makeText(SavedPlanDetailActivity.this, R.string.bu_lottery_tickets_successfully,
								Toast.LENGTH_SHORT).show();
						setResult(RESULT_OK);
						finish();
					} else {
						String dataStr = js.getString("Data");
						if (dataStr.contains("认购失败")) {
							dataStr = "您的当前余额不足，请先充值，再购买投注。" ;
						} 
						new ShowTipDialog().showHBuyInfo(SavedPlanDetailActivity.this,dataStr, "购买失败",
								R.drawable.buy_failure);
						// "您的当前余额不足，请先充值，再购买投注。",
					}
				} catch (JSONException ex) {

				}
			}
		}
	}

	private Map<String, Object> mData;

	class AsyncLoader extends AsyncTask<String, Integer, String> {// 继承AsyncTask
		String action;
		ShowTipDialog showdialog = new ShowTipDialog();

		// 1.准备运行
		protected void onPreExecute() {
			showdialog.showDialog(SavedPlanDetailActivity.this);
		}

		// 2.正在后台运行
		@Override
		protected String doInBackground(String... paramsArr) {
			// 处理后台执行的任务，在后台线程执行
			String strResult = null;

			action = paramsArr[1];
			// 获取请求返回值
			String UserID = ApplicationData.getInstance().getUserID();
			strResult = GetRequestParams.getRequestUserIDResult(paramsArr[0], UserID, action, getApplicationContext());
			// 获取请求返回值
			return strResult;
		}

		// 3.进度更新
		protected void onProgressUpdate(Integer... progress) {
		}

		// 4.完成后台任务
		protected void onPostExecute(String result) {
			if (result != null) {
				try {
					JSONTokener jsonParser = new JSONTokener(result);
					JSONObject js = (JSONObject) jsonParser.nextValue();
					// 接下来的就是JSON对象的操作了
					if (Integer.parseInt(js.getString("Code")) == 0) {
						if (action.equals("210")) {
							mData = getData(result);
							if (mData != null && !mData.equals("")) {
								showDetailContent();
							} else {
								Toast.makeText(SavedPlanDetailActivity.this, R.string.solution_does_not_exist,
										Toast.LENGTH_LONG).show();
							}
							showdialog.closeDialog();
						} else {
							Toast.makeText(SavedPlanDetailActivity.this, js.getString("Data"), Toast.LENGTH_SHORT)
									.show();
						}
					} else {
						Toast.makeText(SavedPlanDetailActivity.this, js.getString("Data"), Toast.LENGTH_SHORT).show();
					}

				} catch (JSONException ex) {
					// 异常处理代码
					Log.e("error", ex.toString());
				} finally {
					showdialog.closeDialog();
				}
			} else {
				Toast.makeText(SavedPlanDetailActivity.this, getString(R.string.problem_01), Toast.LENGTH_LONG).show();
			}
		}

		// 5.完成后操作
		protected void onCancelled() {

		}
	}

	boolean isNotUpload = false;
	boolean isToWeb = false;
	String betContent = "";

	private Map<String, Object> getData(String strResult) {
		Map<String, Object> listmap = new HashMap<String, Object>();
		try {
			JSONTokener jsonParser = new JSONTokener(strResult);
			JSONObject js = (JSONObject) jsonParser.nextValue();
			int code = Integer.parseInt(js.getString("Code"));
			if (code < 0) {
				Toast.makeText(SavedPlanDetailActivity.this, js.getString("Data"), Toast.LENGTH_LONG).show();
				listmap = null;
			} else {
				listmap = ConvertJsonToList.getMap(js.getString("Data"));
				if (listmap.get("LotNumber") != null) {
					if ("未上传".equals(listmap.get("LotNumber").toString())) {
						isNotUpload = true;
					} else {
						isNotUpload = false;
					}
				}
				if (listmap.get("IsShow") != null) {
					if ("false".equals(listmap.get("IsShow").toString())) {
						isToWeb = true;
					}
				}
				try {
					Map<String, Object> lnmap = new HashMap<String, Object>();
					if (listmap.get("LotNumber") != null) {
						if (!"未上传".equals(listmap.get("LotNumber").toString())
								&& !"".equals(listmap.get("LotNumber").toString())) {
							lnmap = ConvertJsonToList.getMap(listmap.get("LotNumber").toString());
							List<Map<String, Object>> lnlist = new ArrayList<Map<String, Object>>();
							if (lnmap.get("item") != null) {
								lnlist = ConvertJsonToList.getList(lnmap.get("item").toString());
							}
							// 名字 及 投注号
							if (lnlist != null) {
								for (int i = 0; i < lnlist.size(); i++) {
									Map<String, Object> map = new HashMap<String, Object>();
									betContent = betContent + "[" + lnlist.get(i).get("PlayTypeName").toString() + "]";
									map.put("PlayTypeName", lnlist.get(i).get("PlayTypeName"));
									String betNum = "";
									if (lnlist.get(i).containsKey("ColorNumber")) {
										betNum = lnlist.get(i).get("ColorNumber").toString();
									} else {
										betNum = lnlist.get(i).get("LotNumber").toString();
									}
									betContent = betContent + "\t" + betNum;
									if (i != (lnlist.size() - 1)) {
										betContent = betContent + "\n";
									}
								}
							}
						}
					}
				} catch (Exception e) {
					// e.printStackTrace();
				}
			}
		} catch (JSONException ex) {
			// 异常处理代码
			Log.e("error", ex.toString());
			listmap = null;
		}
		return listmap;
	}

	public void showDetailContent() {
		// TODO Auto-generated method stub
		tv_savedplan_bet_content.setText(betContent);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			this.finish();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}

	};
}
